<?php

class MessagesController extends AppController {
	public $Helpers = array ('Html' , 'Form' ); 
	public $uses = array('Weibo', 'Comment', 'Thread', 'Message', 'User');

	private function getThread( $uid1 = null, $uid2 = null) {
		$threadId1 = $this->Thread->find('first',
			array('conditions' => array('user1' => $uid1, 'user2' => $uid2)));
		$threadId2 = $this->Thread->find('first',
			array('conditions' => array('user1' => $uid2, 'user2' => $uid1)));

		if ( $threadId1 == null && $threadId2 == null ) {
			$newThread['user1'] = $uid1;
			$newThread['user2'] = $uid2;
			$this->Thread->save($newThread);
			return getThread( $uid1 ,$uid2);
		} else if ( $threadId1 ) {
			return $threadId1;
		} else if ( $threadId2 ) {
			return $threadId2;
		}
	}

	public function index() {
		$thread = $this->Thread->find('all' , array());
		$this->set('thread', $thread);
	}

	public function messageSend( $to = null ) {
		if ( $this->request->is('post') ) {
			$this->Message->create();
			$this->request->data['Message']['date'] = date('Y-m-d H:i:s');

			$this->request->data['Message']['user_form_id'] =
				$this->Session->read('userid');
			$this->request->data['Message']['user_to_id'] = $to;

			$this->request->data['Message']['thread_id'] =
				$this->getThread(
					$this->Session->read('userid'), $to
				);

			if ($this->Message->save($this->request->data)) {
				$this->Session->setFlash(__('Your Message has been send.'));
				return $this->redirect(
					array( 'controller' => 'weibos', 'action' => 'index'));
			}
			$this->Session->setFlash(__('Unable to send your message.'));
		}
	}

	public function messageView( $threadId = null ) {
		$this->set('messages' , $this->Message->find(
			'all',
			array(
				'conditions' => array (
					'thread_id' => $threadId ),
				'order' => 'date DESC'
				)));
	}

}

 ?>
